<?php
class catalog_category_concept extends system_concept_abstract {
	
	public function init() {
		$this->setRowClass('catalog_category_row');
		$this->setModel('catalog_category_model', 'category');
		$this->setJoinLeftModel('common_media_model', 'category.thumb = media.md5', 'media');
		$this->setModelCols('category', array('id', 'parent_id', 'name', 'ename', 'description', 'display_order', 'product_total'));
		$this->setModelCols('category', array('thumb', 'is_active', 'creationtime', 'lastmodified'));
		$this->setModelCols('media', array('md5', 'size', 'type', 'extension'));
	}

	public function save($row) {
		if($row->getName() == null) {
			throw new catalog_exception("Name can not be empty.");
		}
		$row->set('ename', preg_replace('/[^\w-]/is', '', $row->get('ename')));
		if($row->getEname() == null) {
			throw new catalog_exception("English Name can not be empty.");
		}
		
		$row->set('parent_id', intval($row->getParentId()));
		$row->set('display_order', intval($row->getDisplayOrder()));
		if($row->getIsActive() == null) {
			$row->setIsActive(1);
		}
		if($row->getProductTotal() == null) {
			$row->setProductTotal(0);
		}
		
		if($row->getId()) {
			if($this->fetch(array('category.id != ?' => $row->getId(), 'category.ename = ?' => $row->getEname()))) {
				throw new catalog_exception("English Name ({$row->getEname()}) is already existing.");
			}
			$row->setLastmodified(system_date::timestamp());
			$this->getModel('category')->update($row->getModelData('category'), array('id=?' => $row->getId()));
			return $row;
		}
		if($this->fetch(array('category.ename = ?' => $row->getEname()))) {
			throw new catalog_exception("English Name ({$row->getEname()}) is already existing.");
		}
		$row->setLastmodified(system_date::timestamp());
		$row->setCreationtime(system_date::timestamp());
		$id = $this->getModel('category')->insert($row->getModelData('category'));
		$row->setId($id);
		return $row;
	}
	
	public function delete($row) {
		if($this->fetchCount(array('parent_id = ?' => $row->getId())) > 0) {
			throw new catalog_exception("This Category can not be deleted. Please delete all children first.");
		}
		parent::delete($row);
	}

}